<?php

namespace support\spark\exception\handler;

use Tinywan\Jwt\Exception\JwtRefreshTokenExpiredException;
use Tinywan\Jwt\Exception\JwtTokenException;
use Tinywan\Jwt\Exception\JwtTokenExpiredException;
use Webman\Exception\ExceptionHandler;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

class ApiExceptionHandler extends ExceptionHandler
{
    public function report(Throwable $e)
    {
        // TODO: Implement report() method.
    }

    public function render(Request $request, Throwable $e): Response
    {
        if ($e instanceof JwtTokenException || $e instanceof JwtTokenExpiredException || $e instanceof JwtRefreshTokenExpiredException) { //token校验错误
            return json([
                'code' => 403,
                'msg' => $e->getMessage()
            ]);
        }
        if ($e instanceof \ErrorException) {
            $message = [
                'code' => 500,
                'msg' => (config('app.debug') == true) ? $e->getMessage() : "Server internal error",
            ];
            if ((config('app.debug') == true)) {
                $message['track'] = [
                    'file' => $e->getFile() . ':' . $e->getLine(),
                ];
            }
            return json($message);
        }

        // 处理其他异常
        return parent::render($request, $e);
    }

}
